package com.ThreadStudy.ThreadCallable;

import com.ThreadStudy.StudyDemo.TestThreadDown;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/*
* 线程创建方式3
*
* 实现Callable接口
*
* */
public class TestCallable implements Callable<Boolean> {


    private String url; // 网络图片的地址
    private String name; // 保存的文件名

    public  TestCallable(String url,String name){
        this.url=url;
        this.name=name;
    }

    // 下载图片线程的执行体
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为:"+name);
        return true;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t0 = new TestCallable("https://img2020.cnblogs.com/blog/2508133/202109/2508133-20210920182859176-1378059383.png","1.png");
        TestCallable t1 = new TestCallable("https://img2020.cnblogs.com/blog/2508133/202109/2508133-20210920182847694-1327752584.png","2.png");
        TestCallable t2 = new TestCallable("https://img2020.cnblogs.com/blog/2508133/202109/2508133-20210920183237097-1882601877.png","3.png");

        /*
         * 下载了文件名为:3.png
         * 下载了文件名为:2.png
         * 下载了文件名为:1.png
         * */

        // 创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> result0 = executorService.submit(t0);
        Future<Boolean> result1 = executorService.submit(t1);
        Future<Boolean> result2 = executorService.submit(t2);
        // 获取结果
        Boolean r1 = result0.get();
        Boolean r2 = result1.get();
        Boolean r3 = result2.get();

        // 关闭服务

        executorService.shutdownNow();

    }
}


// 下载器
class WebDownloader{
    // 下载方法
    public void downloader(String url,String name) {
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader方法出现的问题");
        }


    }
}